import 'package:flutter/material.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';

import '../app_constant.dart';
import '../base/base_app_bar.dart';
import '../net/network_manager.dart';
import '../net/response/base_response.dart';
import 'package:toast/toast.dart';

class Version extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return VersionPage();
  }
}

class VersionPage extends StatefulWidget {
  @override
  _VersionPageState createState() => _VersionPageState();
}

class _VersionPageState extends State<VersionPage> {
  final _formKey = GlobalKey<FormState>();
  VersionBean versionBean;

  // 下拉菜单更新选择
  void _updateVersionCode() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CommonAppBar(
          title: 'Version',
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: () {
              Navigator.of(context).pop(true);
            },
          ),
        ),
        body: Container(
          color: MyAppTheme.white,
          child: Padding(
            padding: const EdgeInsets.only(left: 15, top: 100, right: 15),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Image.asset(
                    'assets/images/ic_logo.jpg',
                    width: 100,
                    height: 100,
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 5),
                  ),
                  Center(
                    child: FutureBuilder<String>(
                      future: Utils.getAppVersion(),
                      builder: (context, snapshot) {
                        return Text("Version: " + snapshot.data,
                            style: MyAppTheme.body2);
                      },
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 20),
                  ),
                  SizedBox(
                    height: 40, // 高度
                    child: ElevatedButton(
                      child: Text('Check the new version'),
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all<Color>(
                            MyAppTheme.nearlyBlue),
                        shape:
                            MaterialStateProperty.all<RoundedRectangleBorder>(
                          RoundedRectangleBorder(
                            borderRadius:
                                const BorderRadius.all(Radius.circular(20.0)),
                          ),
                        ),
                      ),
                      onPressed: () {
                        getNewAppInfo();
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ));
  }

  void getNewAppInfo() async {
    BaseResponse baseResponse =
        await NetworkManager().request(context,Constants.getNewAppInfo);

    if (baseResponse.status == 200) {
      versionBean = VersionBean.fromJson(baseResponse.data);
      Utils.getAppVersion()
          .then((versionCode) => {getCompare(versionBean, versionCode)});
      // _updateVersionCode();
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg),duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}

class VersionBean {
  String code; //版本号
  String title; //标题
  String descr; //描述
  String fileName; //文件名称
  String url; //地址
  String createdDatetime; //创建时间

  VersionBean(this.code, this.title, this.descr, this.fileName, this.url,
      this.createdDatetime);

  VersionBean.fromJson(Map<dynamic, dynamic> json)
      : code = json['code'] as String,
        title = json['title'] as String,
        descr = json['descr'] as String,
        fileName = json['fileName'] as String,
        url = json['url'] as String,
        createdDatetime = json['createdDatetime'] as String;
}

void getCompare(VersionBean versionBean, String versionName) {
  try {
    String versionCode = versionBean.code;
    if (versionCode.contains(".")) {
      versionCode = versionCode.replaceAll(".", "");
    }

    if (versionName.contains(".")) {
      versionName = versionName.replaceAll(".", "");
    }

    int newCode = int.parse(versionCode);
    int curCode = int.parse(versionName);

    if (newCode > curCode) {
      print("需要升级");
      // getPresenter().getApk(Constants.baseImgUrl + version.getUrl());
      return;
    }
  } catch (e) {
    e.toString();
  }
}
